﻿using System;
using System.Collections.Generic;
using System.Linq;
using cludg.Infrastructure.Core.Attributes;

namespace cludg.Repository.Content.InMemory
{
	using Domain.Content;

	public class ContentRepository<TContent> : IContentRepository<TContent> where TContent: IContent
	{
		protected static readonly List<TContent> Items = new List<TContent>();

		[LogInvoke]
		public IQueryable<TContent> Get() 
		{
			return Items.AsQueryable();
		}

		public TContent ById(string id)
		{
			return Items.FirstOrDefault(x => x.Id == id);
		}

		[LogInvoke]
		public string Add(TContent content)
		{
			if (String.IsNullOrEmpty(content.Id))
			{
				content.Id = Utils.Identity.Generate();
			}
			else
			{
				if (Items.FirstOrDefault(c => (c.Id == content.Id)) != null)
					throw new ApplicationException(String.Format("{0} уже существует!", content.Id));
			}

			Items.Add(content);

			return content.Id;
		}

		[LogInvoke]
		public void Delete(string contentId)
		{
			var content = Items.FirstOrDefault(c => (c.Id == contentId) && (c is TContent));
			if (content == null)
				throw new ApplicationException(String.Format("{0} не существует!", contentId));

			Items.Remove(content);
		}

		[LogInvoke]
		public void Save(TContent content)
		{
			if (Items.Contains(content))
				Items.Remove(content);

			Items.Add(content);
		}
	}
}
